package com.fh.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/*
 * 短信邮箱工具类
 */
public class SendSms {
	  /*
	   * 短信
	   */
    private static String ENCODING = "UTF-8";
    private static String URI_SEND_SMS ="https://sms.yunpian.com/v2/sms/single_send.json";
	  public static String post(String url, Map < String, String > paramsMap) {
	        CloseableHttpClient client = HttpClients.createDefault();
	        String responseText = "";
	        CloseableHttpResponse response = null;
	        try {
	            HttpPost method = new HttpPost(url);
	            if (paramsMap != null) {
	                List < NameValuePair > paramList = new ArrayList <
	                    NameValuePair > ();
	                for (Map.Entry < String, String > param: paramsMap.entrySet()) {
	                    NameValuePair pair = new BasicNameValuePair(param.getKey(),
	                        param.getValue());
	                    paramList.add(pair);
	                }
	                method.setEntity(new UrlEncodedFormEntity(paramList,
	                    ENCODING));
	            }
	            response = client.execute(method);
	            HttpEntity entity = response.getEntity();
	            if (entity != null) {
	                responseText = EntityUtils.toString(entity, ENCODING);
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                response.close();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	        return responseText;
	    }
	  
	  /*
	   * 短信发送方法
	   */
	    public static String sendSms(String apikey, String text, 
	            String mobile) throws IOException {
	            Map < String, String > params = new HashMap < String, String > ();
	            params.put("apikey", apikey); //短信秘钥
	            params.put("text", text);     //发送的文本
	            params.put("mobile", mobile); //电话号码
	            return post(URI_SEND_SMS, params);
	        }
	    
	    /*
	     * 邮箱
	     */
        public static final String SMTPSERVER = "smtphm.qiye.163.com";   //服务器地址
	    public static final String SMTPPORT = "994";              //端口
	    public static final String ACCOUT = "service@union166.com";  //发件人邮箱
	    public static final String PWD = "He6Zuo6.Yxiang";    //密码


	    public static void SendEmail(String email,String title,String text) throws Exception {

	        // 创建邮件配置
	        Properties props = new Properties();
	        props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议（JavaMail规范要求）
	        props.setProperty("mail.smtp.host", SMTPSERVER); // 发件人的邮箱的 SMTP 服务器地址
	        props.setProperty("mail.smtp.port", SMTPPORT); 
	        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	        props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
	        props.setProperty("mail.smtp.ssl.enable", "true");// 开启ssl


	        // 根据邮件配置创建会话，注意session别导错包
	        Session session = Session.getDefaultInstance(props);
	        // 开启debug模式，可以看到更多详细的输入日志
	        session.setDebug(true);
	        //创建邮件
	        MimeMessage message = createEmail(session,email,title,text);
	        //获取传输通道
	        Transport transport = session.getTransport();
	        transport.connect(SMTPSERVER,ACCOUT, PWD);
	        //连接，并发送邮件
	        transport.sendMessage(message, message.getAllRecipients());
	        transport.close();

	    }


	    public static MimeMessage createEmail(Session session,String email,String title,String text) throws Exception {
	        // 根据会话创建邮件
	        MimeMessage msg = new MimeMessage(session);
	        // address邮件地址, personal邮件昵称, charset编码方式
	        InternetAddress fromAddress = new InternetAddress(ACCOUT,
	                "联盟网", "utf-8");
	        // 设置发送邮件方
	        msg.setFrom(fromAddress);
	        InternetAddress receiveAddress = new InternetAddress(//
	        		email, "test", "utf-8");
	        // 设置邮件接收方
	        msg.setRecipient(RecipientType.TO, receiveAddress);
	        // 设置邮件标题
	        msg.setSubject(title, "utf-8");
	        msg.setText(text);
	        // 设置显示的发件时间
	        msg.setSentDate(new Date());
	        // 保存设置
	        msg.saveChanges();
	        return msg;
	    }
	    
}
